package com.attendance.www.hr.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.RequestInterfaceTask;
import com.attendance.www.hr.entitys.SystemConfigure;
import com.attendance.www.hr.service.IRequestInterfaceTaskService;

import net.sf.json.JSONObject;

/**
 * 
 * @author 主数据请求
 *
 */

public class HttpRequestMain {
	
	/**
	 * 向指定 URL 发送POST方法的请求
	 * @param interfaceName
	 * @param type  类型
	 * @param url   地址
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @param token 秘钥
	 * @param user  用户名称
	 * @param password 密码
	 * @param startDate 同步主数据开始日期
	 * @param requestInterfaceTaskService
	 * @return
	 */
	public static String sendPost(String interfaceName,
								  Integer type,	
								  String url, 
								  JSONObject param,
								  String token,
								  String user,
								  String password,
								  Date startDate,
								  IRequestInterfaceTaskService requestInterfaceTaskService,
								  List<Employee> employeeList,
								  SystemConfigure systemConfigure) {
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        String result = null;
        RequestInterfaceTask requestInterfaceTask=new RequestInterfaceTask();
        Integer ritId=null;
        String encoding = "UTF-8";
        byte[] data = null;
        
        try {
        	//新增请求接口日志
        	requestInterfaceTask.setInterfaceName(interfaceName);
        	requestInterfaceTask.setStartDate(startDate);
        	requestInterfaceTask.setState(1);
        	requestInterfaceTask.setType(type);
        	ritId=requestInterfaceTaskService.saveRequestInterfaceTask(requestInterfaceTask);
        	
        	//发起请求
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json; charset=" + encoding);
            
            if(user!=null && password!=null) {
            	//Authorization验证
               	String authString = user + ":" + password;
            	@SuppressWarnings("restriction")
				String code = new sun.misc.BASE64Encoder().encode(authString.getBytes());
            	String authStringEnc = new String(code);
            	conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
            }
            
            //设置请求参数长度
            if(param!=null) {
	         	data = (param.toString()).getBytes(encoding);
	            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            }
            
            //配置token属性
            if(token!=null) {
                conn.setRequestProperty("Authorization", "Bearer " + token);
            }

            conn.setConnectTimeout(50000);
            conn.setReadTimeout(50000);
            // 默认为false,post方法需要写入参数,设定true
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
			conn.setDoOutput(true);
			
            //发送请求参数
            if(param!=null) {
                // 获取URLConnection对象对应的输出流
                OutputStream outStream = conn.getOutputStream();
                outStream.write((param.toString()).getBytes());
                outStream.flush();
                outStream.close();
            }

            // 获取连接状态码
         	int recode = conn.getResponseCode();
         	if (recode == 200) {
         		
                // 定义BufferedReader输入流来读取URL的响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),encoding));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    sb.append(lines);
                }
                result=sb.toString();
                reader.close();
                
                //写入请求失败日志
         		requestInterfaceTask.setRitId(ritId);
                requestInterfaceTask.setEndDate(new Date());
                requestInterfaceTask.setState(2);
                requestInterfaceTaskService.updataRequestInterfaceTask(requestInterfaceTask);
                
         	}else {
         		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(),encoding));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                	sb.append(lines);
                }
                result=sb.toString();
                reader.close();
         		
         		//写入请求失败日志
         		requestInterfaceTask.setRitId(ritId);
                requestInterfaceTask.setEndDate(new Date());
                requestInterfaceTask.setState(3);
                requestInterfaceTask.setErrorDescription(recode+"："+result);
                requestInterfaceTaskService.updataRequestInterfaceTask(requestInterfaceTask);
                HttpRequestMain.mailSend(interfaceName, type, employeeList, systemConfigure);
         	}
        } catch (Exception e) {
        	//写入请求失败日志
            System.out.println("发送 POST 请求出现异常！"+e);
            requestInterfaceTask.setRitId(ritId);
            requestInterfaceTask.setEndDate(new Date());
            requestInterfaceTask.setState(3);
            requestInterfaceTask.setErrorDescription(e.getMessage());
            requestInterfaceTaskService.updataRequestInterfaceTask(requestInterfaceTask);
            HttpRequestMain.mailSend(interfaceName, type, employeeList, systemConfigure);
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
                if (conn != null) {
                	// 关闭连接
    				conn.disconnect();
                } 
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
	
	/**
	 * 请求失败发送错误邮件
	 * @param interfaceName
	 * @param type
	 * @param employeeList
	 * @param systemConfigure
	 */
	public static void mailSend(String interfaceName,Integer type,List<Employee> employeeList,SystemConfigure systemConfigure) {
         //循环发送邮件给相关负责人
         for(int i=0;i<employeeList.size();i++) {
         	Employee employee=employeeList.get(i);
         	String textPart="";
         	String mailStr=null;
         	if(type==0 || type==1 || type==2) {
         		mailStr=MailUtils.toGBK(AppConstant.MAIN_MAIL_CONTENTONE);
         	}else {
         		mailStr=MailUtils.toGBK(AppConstant.MAIN_MAIL_CONTENTTWO);
         	}
         	textPart=textPart+mailStr.replace("@1",interfaceName);
         	//发邮件
         	MailUtils.send(systemConfigure, employee.getEmail(), AppConstant.MAIL_TITLE,textPart, AppConstant.MAIL_ENDING);
         }
	}
}
